﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FatHibernation.Data.exceptions;
using FatHibernation.DataInterface;
using FatHibernation.Utilities.DesignByContract;


namespace FatHibernation.Data
{
    public class DataRepository : IDataRepository
    {


        public NHibernate.ICriteria CreateCriteria<T>() where T : ISavable
        {
            VerifySessionAndTransaction();
            return DataContextStorage.Session.CreateCriteria(typeof(T));
        }

        public NHibernate.IQuery CreateQuery(string hql)
        {
            VerifySessionAndTransaction();
            return DataContextStorage.Session.CreateQuery(hql);
        }

        public T Load<T>(int ID) where T : ISavable
        {
            VerifySessionAndTransaction();
            return DataContextStorage.Session.Get<T>(ID); ;
        }

        public void Delete(ISavable bo)
        {
            VerifySessionAndTransaction();
            DataContextStorage.Session.Delete(bo);
        }

        public void Save(ISavable bo)
        {
            VerifySessionAndTransaction();
            DataContextStorage.Session.Save(bo);

            Check.Ensure(bo.ID != 0, "Save should set ID!");
        }

        private static void VerifySessionAndTransaction()
        {
            if (DataContextStorage.Session == null)
                throw new OutsideSessionException();
            if (DataContextStorage.CurrentTransaction == null)
                throw new OutsideTransactionException();
        }

    }
}
